package com.prtek.reminder.model;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import com.prtek.reminder.Constant;
import com.prtek.reminder.bean.DaoMaster;
import com.prtek.reminder.bean.DaoSession;
import com.prtek.reminder.bean.Notes;
import com.prtek.reminder.bean.NotesDao;
import com.prtek.reminder.bean.NotesJoinUser;
import com.prtek.reminder.bean.NotesJoinUserDao;
import com.prtek.reminder.helper.UpgradeHelper;
import java.io.File;
import java.util.List;
import org.greenrobot.greendao.database.Database;

/**
 * Created by jarly on 2018/9/7.
 */

public class ReminderDaoImpl implements ReminderDao {

  private DaoSession mDaoSession;
  private UpgradeHelper mHelper;
  private Context mContext;
  private Database mDatabase;
  private NotesDao mNotesDao;
  private NotesJoinUserDao mNotesJoinUserDao;

  private ReminderDaoImpl() {
  }

  @Override public void initialize(Context context) {
    mHelper = UpgradeHelper.getInstance(context);
    mContext = context;
    mDatabase = mHelper.getWritableDb();
    mDaoSession = new DaoMaster(mDatabase).newSession();
    mNotesDao = mDaoSession.getNotesDao();
    mNotesJoinUserDao = mDaoSession.getNotesJoinUserDao();
  }

  @Override public void deleteNotes(Notes notes) {

    mNotesJoinUserDao.queryBuilder()
        .where(NotesJoinUserDao.Properties.NotesId.eq(notes.getId()))
        .buildDelete()
        .executeDeleteWithoutDetachingEntities();
    if (notes.getDescType() == Constant.DESC_AUDIO) {
      File file = new File(notes.getExpireDate());
      file.delete();
    }
    mNotesDao.delete(notes);
    notifyChage();
  }

  @Override public void insertNotes(Notes notes) {
    mNotesDao.insert(notes);
    notifyChage();
  }

  @Override public void addNotesJoinUser(NotesJoinUser joinUser) {
    mNotesJoinUserDao.insert(joinUser);
  }

  @Override public List<Notes> getNotesList() {

    return mNotesDao.queryBuilder().list();
  }

  @Override public List<Notes> getExpiredNotesList(long time) {
    return mNotesDao.queryBuilder().where(NotesDao.Properties.EndTimes.le(time)).orderAsc().list();
  }

  @Override public Notes getNotesById(long id) {
    return null;
  }

  interface InstanceHolder {
     ReminderDao instance = new ReminderDaoImpl();
  }

  private void notifyChage() {
    mContext.getContentResolver().notifyChange(UpgradeHelper.CONTENT_URI, null);
  }

  public SQLiteDatabase getDatabase(Context context) {
    mHelper = UpgradeHelper.getInstance(context);
    return mHelper.getWritableDatabase();
  }

  public static ReminderDao getInstance() {
    return InstanceHolder.instance;
  }

  public DaoSession getDaoSession() {
    return mDaoSession;
  }
}
